from datetime import datetime
from sensor.sensor import Sensor
from sensor.frame import Frame
import serial


class RealSensor(Sensor):
    def __init__(self, port: str, baudrate: int):
        try:
            self.serial = serial.Serial(port, baudrate, timeout=1)
        except:
            print("Failed to open serial port[", port, "]")
            return
        print("Serial port[", port, "] opened successfully")
    
    def Open(self)->bool:
        if not self.serial.is_open:
            self.serial.open()
        return self.serial.is_open

    def Read(self) -> Frame:
        raw = self.serial.readline()
        valueStrs = raw.decode().strip()
        if valueStrs != "":
            frame = Frame()
            frame.DecodeFromStringWithTime(valueStrs, datetime.now())
            return frame
        else:
            #print("Empty")
            return None

    def Close(self):
        self.serial.close()

    def __del__(self):
        self.Close()


if __name__ == "__main__":
    sensor = RealSensor("COM3", 9600)
    while True:
        print(sensor.read())
